from apps.goods.models import GoodsChannel


def get_fenlei():
    categories_dict = dict()  # 创建一个字典
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    # print(channels)
    for channel in channels:  # 遍历出每个频道
        group_id = channel.group_id  # 取出当前频道的id
        if group_id not in categories_dict:  # 判断当前频道的id是不是在字典中
            categories_dict[group_id] = {'channels': [], 'sub_cats': []}
        category_1 = channel.category  # 获取商品的分类
        categories_dict[group_id]['channels'].append({
            'id': category_1.id,
            'name': category_1.name,
            'url': channel.url
        })  # 添加一级分类
        # 构建二级分类
        for category_2 in category_1.subs.all():
            category_2_dict = {'id': category_2.id, 'name': category_2.name, 'sub_cats': []}
            for category_3 in category_2.subs.all():
                category_3_dict = {'id': category_3.id, 'name': category_3.name}
                category_2_dict['sub_cats'].append(category_3_dict)
            categories_dict[group_id]['sub_cats'].append(category_2_dict)
    return categories_dict


def get_breadcrumb(category):
    """
    获取面包屑导航
    :param category: 商品类别
    :return: 面包屑导航字典
    """
    breadcrumb = dict(
        category_1='',
        category_2='',
        category_3=''
    )
    if category.parent is None:
        # 当前类别为一级类别
        breadcrumb['category_1'] = category
    elif category.subs.count() == 0:
        # 当前类别为三级
        breadcrumb['category_3'] = category
        cat2 = category.parent
        breadcrumb['category_2'] = cat2
        breadcrumb['category_1'] = cat2.parent
    else:
        # 当前类别为二级
        breadcrumb['category_2'] = category
        breadcrumb['category_1'] = category.parent

    return breadcrumb
    # bread = dict(
    #     category_1="",
    #     category_2="",
    #     category_3="",
    # )
    # if category.parent is None:
    #     # 判断是否属于第一类别
    #     bread['category_1'] = category
    # elif category.subs.count()==0:
    #     # 判断是否属于第三类别

